import type { Ref } from 'vue';
import { computed, watch } from 'vue';
import { allowMultipleToast, showLoadingToast } from 'vant';
import type { ToastWrapperInstance } from 'vant';

export function useToastLoading(watchLoading: Ref<boolean> | Ref<boolean>[]) {
  // Toast多例模式
  allowMultipleToast();
  let toast: ToastWrapperInstance | null = null;
  const loading = Array.isArray(watchLoading)
    ? computed(() => watchLoading.every((v) => v.value))
    : computed(() => watchLoading.value);
  watch(
    () => loading.value,
    () => {
      if (loading.value) {
        toast = showLoadingToast({
          message: '加载中...',
          forbidClick: true,
        });
      } else {
        toast?.close();
      }
    },
    {
      immediate: true,
    }
  );
}
